package com.jqh.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jqh.demo.entity.AclRole;
import com.jqh.demo.entity.AclRoleMenu;
import com.jqh.demo.entity.AclUserRole;
import com.jqh.demo.mapper.AclRoleMapper;
import com.jqh.demo.service.AclRoleMenuService;
import com.jqh.demo.service.AclRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jqh.demo.service.AclUserRoleService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 角色表 服务实现类
 * </p>
 *
 * @author jqh
 * @since 2021-05-08
 */
@Service
public class AclRoleServiceImpl extends ServiceImpl<AclRoleMapper, AclRole> implements AclRoleService {

    @Autowired
    private AclUserRoleService aclUserRoleService;

    @Autowired
    private AclRoleMenuService aclRoleMenuService;

    @Override
    public void pageQuery(Page<AclRole> page, String roleName) {
        QueryWrapper<AclRole> queryWrapper=new QueryWrapper<>();
        //按创建时间进行排序
        queryWrapper.orderByDesc("gmt_create");
        //判断是否存在条件
        if(StringUtils.isEmpty(roleName)){
            baseMapper.selectPage(page,queryWrapper);
            return;
        }
        //存在条件,则添加到wrapper
        queryWrapper.like("role_name",roleName);
        baseMapper.selectPage(page,queryWrapper);

    }

    @Override
    public List<AclRole> getRoleByUserId(String userId) {
        List<AclUserRole> roleIdList = aclUserRoleService.list(new QueryWrapper<AclUserRole>().eq("user_id", userId).select("role_id"));
        List<AclRole> aclRoleList=new ArrayList<>();
        for (AclUserRole aclUserRole : roleIdList) {
            AclRole aclRole = baseMapper.selectById(aclUserRole.getRoleId());
            aclRoleList.add(aclRole);
        }
        return aclRoleList;
    }

    @Override
    public boolean removeRoleWithMid(String id) {
        //删除角色
        baseMapper.deleteById(id);
        //删除用户-角色中间表数据
        aclUserRoleService.remove(new QueryWrapper<AclUserRole>().eq("role_id",id));
        //删除角色-菜单中间表数据
        aclRoleMenuService.remove(new QueryWrapper<AclRoleMenu>().eq("role_id",id));
        return true;
    }

    @Override
    public boolean removeByIdsWithMid(List<String> idList) {
        //删除中间表数据
        for (String id : idList) {
            aclRoleMenuService.remove(new QueryWrapper<AclRoleMenu>().eq("role_id",id));
            aclUserRoleService.remove(new QueryWrapper<AclUserRole>().eq("role_id",id));
        }
        int i = baseMapper.deleteBatchIds(idList);
        if(i>0){
            return true;
        }
        return false;
    }
}
